<?php

	class source
	{

		var $fw		= null;
		var $sec	= null;

		function source(&$framework, &$security)
		{

			$this->fw	= &$framework;
			$this->sec	= &$security;

			switch($this->fw->do)
			{

				case 'graph':
					$this->generate_graph();
					break;

				case 'genres':
				case 'genre':
					//- graph of last 365 days, and when movies where added: perhaps in the genre section?
					$this->show_genres();
					break;

				case 'members':
				case 'member':
					//- avg number of movies owned by members: in the members section
					$this->show_members();
					break;

				default:
					$this->show_stats_main();
					break;

			}

		}

		function generate_graph()
		{
			require_once _BASE_PATH .'/includes/classes/drivers/libchart/libchart.php';

			switch($_GET['type']) {
				case 'moviespergenre':
					$this->_graph_movies_per_genre();
					break;
				case 'moviesperyear':
					$this->_graph_movies_per_year();
					break;
			}
			exit;
		}

		function show_stats_main()
		{

			// Paper Chain
			$this->fw->pc_item('Statistics', 'Statistics about MM, your collection &amp; wishlist', 'index.php?what=statistics');
			$this->fw->template	= 'stats.main.tpl';

			// get stats data
			$this->fw->content['directors'] = $this->_num_directors();
			$this->fw->content['actors']	= $this->_num_actors();
			$this->fw->content['writers']	= $this->_num_writers();
			$this->fw->content['movies']	= $this->fw->number_of_movies();

			// popular
			$this->fw->content['popular']['views']	= $this->_movies_by_views(10);
			$this->fw->content['popular']['ratings']	= $this->_movies_by_ratings(10);

			// figure out the runtime data
			$minutes	= $this->_sum_runtime();
			$runtime	= array('hours' => floor($minutes / 60),
								'minutes' => ($minutes % 60), // remainder
								'total' => $minutes);
			$this->fw->content['runtime'] = $runtime;
			$this->fw->content['runtime_avg'] = $this->_avg_runtime();

			// new movies
			$this->fw->content['new']	= $this->_new_movies();
		}

		// get the number of unique directors from the database
		function _num_directors()
		{
			$sql	= $this->fw->_pq("SELECT COUNT(DISTINCT name_id) FROM #__lnk_movie_directors");
			$result	= mysql_query($sql) or die(mysql_error());
			return mysql_result($result, 0, 0);
		}

		// get the number of unique actors from the database
		function _num_actors()
		{
			$sql	= $this->fw->_pq("SElECT COUNT(DISTINCT name_id) FROM #__lnk_movie_actors");
			$result	= mysql_query($sql) or die(mysql_error());
			return mysql_result($result, 0, 0);
		}

		// get the number of unique writers from the database
		function _num_writers()
		{
			$sql	= $this->fw->_pq("SELECT COUNT(DISTINCT name_id) FROM #__lnk_movie_writers");
			$result	= mysql_query($sql) or die(mysql_error());
			return mysql_result($result, 0, 0);
		}

		function _sum_runtime()
		{
			$sql	= $this->fw->_pq("SELECT SUM(movie_runtime) FROM #__movies");
			$result	= mysql_query($sql) or die(mysql_error());
			return mysql_result($result, 0, 0);
		}

		function _avg_runtime()
		{
			$sql	= $this->fw->_pq("SELECT AVG(movie_runtime) FROM #__movies WHERE movie_runtime > 0");
			$result	= mysql_query($sql) or die(mysql_error());
			$avg = mysql_result($result, 0, 0);
			return (is_numeric($avg)) ? $avg : 0;
		}

		// retreive the top # movies based on the number of views
		function _movies_by_views($num)
		{
			$sql	= $this->fw->_pq("SELECT m.movie_id, m.movie_title, m.movie_imdb, m.movie_year, m.movie_views, COUNT(o.movie_id) AS owners FROM #__movies m LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id GROUP BY m.movie_id ORDER BY m.movie_views DESC, m.movie_title ASC LIMIT %s", (int)$num);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result)) {
				$results[]	= array('id'			=> $row['movie_id'],
									'title'			=> $row['movie_title'],
									'imdb'			=> $row['movie_imdb'],
									'imdb_url'		=> $this->fw->imdb_url($row['movie_imdb']),
									'year'			=> $row['movie_year'],
									'views'			=> $row['movie_views'],
									'owners'		=> $row['owners']);
			}

			return isset($results) ? $results : false;
		}

		function _movies_by_ratings($num)
		{
			// use member ratings if they are turned on
			if($this->fw->config['ratings'] == '1') {
				$field = 'm.movie_rating';
			} else {
				$field = 'm.movie_imdb_rating';
			}

			$sql	= $this->fw->_pq("SELECT m.movie_id, m.movie_title, m.movie_imdb, m.movie_year, m.movie_rating, m.movie_rating_votes, m.movie_imdb_rating, COUNT(o.movie_id) AS owners FROM #__movies m LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id GROUP BY m.movie_id ORDER BY ". $field ." DESC, m.movie_title ASC LIMIT %s", (int)$num);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result)) {
				$results[]	= array('id'			=> $row['movie_id'],
									'title'			=> $row['movie_title'],
									'imdb'			=> $row['movie_imdb'],
									'imdb_url'		=> $this->fw->imdb_url($row['movie_imdb']),
									'year'			=> $row['movie_year'],
									'ratings'		=> ($this->fw->config['ratings'] == '1' ? $row['movie_rating'] : $row['movie_imdb_rating']),
									'rating_votes'	=> $row['movie_rating_votes'],
									'owners'		=> $row['owners']);
			}

			return isset($results) ? $results : false;
		}

		// get a list of movies added this month
		function _new_movies()
		{
			// figure out our date
			$year	= date('Y');
			$month = (int)date('m');
			$date = mktime(0, 0, 0, $month, 1, $year);// unix time stamp of first day of current month

			$sql	= $this->fw->_pq("SELECT m.movie_id, m.movie_title, m.movie_imdb, m.movie_year, m.movie_created, COUNT(o.movie_id) AS owners FROM #__movies m LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id WHERE m.movie_created >= %s GROUP BY m.movie_id ORDER BY m.movie_created DESC, m.movie_title ASC", $date);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result)) {
				$results[]	= array('id'			=> $row['movie_id'],
									'title'			=> $row['movie_title'],
									'imdb'			=> $row['movie_imdb'],
									'imdb_url'		=> $this->fw->imdb_url($row['movie_imdb']),
									'year'			=> $row['movie_year'],
									'created'		=> $row['movie_created'],
									'owners'		=> $row['owners']);
			}
			return isset($results) ? $results : false;
		}

		// get a list of genre's and the number of movies in each genre
		function _genre_count()
		{
			$sql	= $this->fw->_pq("SELECT genre_id as id, genre_name as name, genre_movie_count as count FROM #__genre ORDER BY genre_movie_count DESC");
			$result	= mysql_query($sql) or die(mysql_error());
			while($row = mysql_fetch_assoc($result)) {
				$results[]	= $row;
			}
			return isset($results) ? $results : false;
		}

		function _year_count($limit = 10)
		{
			$sql	= $this->fw->_pq("SELECT COUNT(*) AS `count` , `movie_year` AS `year` FROM `#__movies` GROUP BY `movie_year` ORDER BY `year` DESC LIMIT %s", (int)$limit);
			$result	= mysql_query($sql) or die(mysql_error());
			while($row = mysql_fetch_assoc($result)) {
				$results[] = $row;
			}
			return isset($results) ? $results : false;
		}

		// generate a pie graph for the number of movies per genre
		function _graph_movies_per_genre()
		{
			$chart = new PieChart();

			$genres = $this->_genre_count();
			// reformat the array for the graph class
			foreach($genres as $v) {
				$chart->addPoint(new Point($v['name'], $v['count']));
			}
			header('Content-Type: image/png');
			$chart->render();
		}

		function _graph_movies_per_year()
		{
			$chart = new VerticalChart();
			$years = $this->_year_count(25);
			foreach($years as $v) {
				$chart->addPoint(new Point($v['year'], $v['count']));
			}
			header('Content-Type: image/png');
			$chart->render();
		}

	}

?>